// 页面加载完成后加载订单数据
$(document).ready(function() {
    // 初始化页面
	$('#all-orders').addClass('active show');
    loadOrders(0); // 默认加载全部订单
    
    // 选项卡切换事件
    $('#orderTabs .nav-link').on('click', function() {
        $('#orderTabs .nav-link').removeClass('active');
        $(this).addClass('active');
        
        const type = $(this).data('type');
        
        $('.tab-pane').removeClass('active show');
        const container = getContainerByType(type);
        container.addClass('active show');
        
        loadOrders(type);
    });
    
    function updatePendingCount() {
        $.ajax({
            url: 'order',
            type: 'GET',
            data: { type: 1 }, // 只获取待发货订单
            dataType: 'json',
            success: function(orders) {
                $('#pending-count').text(orders.length);
            }
        });
    }
    
    function generateTrackingNumber() {
        const prefixes = ['SF', 'YT', 'ST', 'YD', 'ZT', 'EMS', 'JD'];
        const prefix = prefixes[Math.floor(Math.random() * prefixes.length)];
        
        let numbers = '';
        for (let i = 0; i < 12; i++) {
            numbers += Math.floor(Math.random() * 10);
        }
        
        const letters = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
        let suffix = '';
        const addSuffix = Math.random() > 0.7;
        if (!addSuffix) {
            const suffixLength = Math.random() > 0.5 ? 1 : 2;
            for (let i = 0; i < suffixLength; i++) {
                suffix += letters.charAt(Math.floor(Math.random() * letters.length));
            }
        }
        
        return `${prefix}${numbers}${suffix}`;
    }

    // 绑定发货按钮事件
    $(document).on('click', '.btn-ship:not(:disabled)', function() {
        const orderCard = $(this).closest('.order-card');
        const orderId = orderCard.find('.order-id').text().split(':')[1].trim();
        
        let trackingNumber = generateTrackingNumber();
        
        $.ajax({
            url: 'shipOrder',
            type: 'POST',
            data: {
                orderId: orderId,
                trackingNumber: trackingNumber
            },
            success: function(response) {
                if (response.success) {
                    alert(`订单 ${orderId} 已发货`);
                    const activeTab = $('#orderTabs .nav-link.active');
                    const type = activeTab.data('type');
                    loadOrders(type);
                    updatePendingCount();
                } else {
                    alert(response.message || '发货失败');
                }
            },
            error: function() {
                alert('发货失败，请重试');
            }
        });
    });
    
 // 精确绑定删除按钮（物理删除）
    $(document).on('click', '.btn-delete-product', function() {
        const goodsId = $(this).data('goods-id');
        const card = $(this).closest('.order-card');
        if (confirm(`确定要永久删除商品 ${goodsId} 吗？此操作不可恢复！`)) {
            $.ajax({
                url: 'deleteProduct',
                type: 'POST',
                data: { 
                    goodsId: goodsId  // 关键修复：使用 goodsId 参数名
                },
                success: function(response) {
                    if (response.success) {
                        alert(`商品 ${goodsId} 已成功删除`);
                        card.fadeOut(500, function() {
                            $(this).remove();
                            if ($('#onshelf .order-card').length === 0) {
                                $('#onshelf').html(`
                                    <div class="empty-orders text-center py-5">
                                        <i class="fas fa-box-open fa-3x text-muted mb-3"></i>
                                        <h4 class="mb-2">暂无上架商品</h4>
                                        <p class="text-muted mb-4">您还没有上架的商品，快去添加吧！</p>
                                        <a href="addProduct.jsp" class="btn btn-primary">
                                            <i class="fas fa-plus-circle me-2"></i>添加商品
                                        </a>
                                    </div>
                                `);
                            }
                        });
                    } else {
                        alert(response.message || '删除失败');
                    }
                },
                error: function() {
                    alert('删除失败，请重试');
                }
            });
        }
    });
    
    // 精确绑定下架按钮（状态变更）
    $(document).on('click', '.btn-off-shelf', function() {
        const goodsId = $(this).data('goods-id');
        const card = $(this).closest('.order-card');
        
        if (confirm(`确定要下架商品 ${goodsId} 吗？下架后商品将不再显示`)) {
            $.ajax({
                url: 'offShelf',
                type: 'POST',
                data: { goodsId: goodsId },
                success: function(response) {
                    if (response.success) {
                        alert(`商品 ${goodsId} 已下架`);
                        card.fadeOut(500, function() {
                            $(this).remove();
                            if ($('#onshelf .order-card').length === 0) {
                                $('#onshelf').html(`
                                    <div class="empty-orders">
                                        <i class="fas fa-box-open"></i>
                                        <h4>暂无上架商品</h4>
                                        <p class="text-muted">您还没有上架的商品，快去添加吧！</p>
                                        <a href="addProduct.jsp" class="btn btn-primary mt-3">添加商品</a>
                                    </div>
                                `);
                            }
                        });
                    } else {
                        alert(response.message || '下架失败');
                    }
                },
                error: function() {
                    alert('下架失败，请重试');
                }
            });
        }
    });
 // 修改商品事件处理
    $(document).on('click', '.btn-edit-product', function() {
        const goodsId = $(this).data('goods-id');
        // 跳转到添加商品页面并传递商品ID
        window.location.href = 'addProduct.jsp?goodsId=' + goodsId;
    });
   
});

// 加载订单数据
function loadOrders(type) {
    const container = getContainerByType(type);
    container.html('<div class="loading-spinner"><div class="spinner"></div></div>');
    
    $.ajax({
        url: 'order',
        type: 'GET',
        data: { type: type },
        dataType: 'json',
        
        success: function(orders) {
            renderOrders(orders, type);
            
            if (type === 0) {
                const pendingCount = orders.filter(o => o.orderType === 1).length;
                $('#pending-count').text(pendingCount);
            }
        },
        error: function(xhr) {
            let errorMsg = '加载订单失败，请重试';
            if (xhr.status === 500) {
                errorMsg = '服务器错误: ' + xhr.responseText;
            } else if (xhr.status === 401) {
                errorMsg = '用户未登录，请重新登录';
               // window.location.href = '';
            }
            container.html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> ${errorMsg}
                    <button class="btn btn-warning mt-2" onclick="loadOrders(${type})">重新加载</button>
                </div>
            `);
        }
    });
}

// 根据类型获取容器
function getContainerByType(type) {
    switch(type) {
        case 0: return $('#all-orders');
        case 1: return $('#pending');
        case 2: return $('#shipped');
        case 3: return $('#completed');
        case 4: return $('#canceled');
        case 5: return $('#onshelf');
        default: return $('#all-orders');
    }
}


// 渲染订单数据
function renderOrders(orders, type) {
    const container = getContainerByType(type);
    container.empty();
    
    if (orders.length === 0) {
        let emptyHtml = '';
        
        if (type === 5) {
            emptyHtml = `
                 <div class="empty-orders text-center py-5">
		            <i class="fas fa-box-open fa-3x text-muted mb-3"></i>
		            <h4 class="mb-2">暂无上架商品</h4>
		            <p class="text-muted mb-4">您还没有上架的商品，快去添加吧！</p>
		            <a href="addProduct.jsp" class="btn btn-primary">
		                <i class="fas fa-plus-circle me-2"></i>添加商品
		            </a>
		        </div>
            `;
        } else {
            emptyHtml = `
                <div class="empty-orders">
                    <i class="fas fa-box-open"></i>
                    <h4>暂无相关订单</h4>
                    <p class="text-muted">您还没有相关状态的订单，快去逛逛吧！</p>
                    <button class="btn btn-primary mt-3">去首页逛逛</button>
                </div>
            `;
        }
        
        container.append(emptyHtml);
        return;
    }
    
    orders.forEach(order => {
        const statusClass = getStatusClass(order.orderType);
        const statusText = getStatusText(order.orderType);
        const actions = getActions(order.orderType, order);
        const metaInfo = getMetaInfo(order, type);
        
        const orderHtml = `
            <div class="order-card">
                <div class="order-header">
                    <div class="order-info">
                        <span class="order-id">${type === 5 ? '商品ID' : '订单号'}: ${type === 5 ? order.goodsId : order.orderId}</span>
                        
                    </div>
                    <span class="order-status ${statusClass}">${statusText}</span>
                </div>
                <div class="order-body">
                    <div class="product-info">
                        <img src="${order.goodImg}" alt="商品图片" class="product-img">
                        <div class="product-details">
                            <h5 class="product-title">${order.goodName}</h5>
                            <p class="product-description">${order.goodDesc}</p>
                            <div class="product-price">¥${order.goodPrice.toFixed(2)}</div>
                        </div>
                    </div>
                    <div class="order-meta">
                        ${metaInfo}
                    </div>
                    <div class="order-actions">
                        ${actions}
                    </div>
                </div>
            </div>
        `;
        
        container.append(orderHtml);
    });
}

// 获取状态类名
function getStatusClass(type) {
    switch(type) {
        case 1: return 'status-pending';
        case 2: return 'status-shipped';
        case 3: return 'status-completed';
        case 4: return 'status-canceled';
        case 5: return 'status-onshelf';
        default: return '';
    }
}

// 获取状态文本
function getStatusText(type) {
    switch(type) {
        case 1: return '已完成';
        case 2: return '待发货';
        case 3: return '已取消';
        case 4: return '待付款';
        case 5: return '已上架'; 
        default: return '未知状态';
    }
}

// 获取操作按钮
function getActions(type, order) {
    switch(type) {
        case 2: // 待发货 -> 卖家操作
            return `
                <button class="btn btn-ship">发货</button>
                <button class="btn btn-cancel">取消订单</button>
            `;
        case 1: // 已完成 -> 无操作
            return ''; 
        case 3: // 已取消 -> 无操作
            return ''; 
        case 4: // 待付款 -> 无操作
            return '';
        case 5: // 已上架 -> 商品操作
            return `
                <button class="btn btn-edit-product" data-goods-id="${order.goodsId}">修改商品</button>
                <button class="btn btn-delete-product" data-goods-id="${order.goodsId}">删除商品</button>
            `;
        default:
            return '';
    }
}

// 获取元信息
function getMetaInfo(order, type) {
    let metaHtml = '';
    
    // 公共信息
    if (type !== 5) { // 订单相关商品显示实付款
        metaHtml += `
            <div class="meta-group">
                <span class="meta-label">实付款:</span>
                <span class="text-danger fw-bold">¥${order.goodPrice.toFixed(2)}</span>
            </div>
        `;
    }
    
    // 订单类型特定信息
    switch(type) {
    case 2: // 待发货
        metaHtml += `
            <div class="meta-group">
                <span class="meta-label">收货地址:</span>
                <span>${order.address || '地址未填写'}</span>
            </div>
        `;
        break;
        
    case 1: // 已完成
        metaHtml += `
            <div class="meta-group">
                <span class="meta-label">快递:</span>
                <span>${order.packageNum || '未填写快递单号'}</span>
            </div>
            <div class="meta-group">
                <span class="meta-label">收货时间:</span>
                <span>${formatDate(order.receiveTime)}</span>
            </div>
        `;
        break;
        
    case 3: // 已取消
        const cancelReason = getCancelReason(order);
        metaHtml += `
            <div class="meta-group">
                <span class="meta-label">取消原因:</span>
                <span>${cancelReason}</span>
            </div>
            <div class="meta-group">
                <span class="meta-label">取消时间:</span>
                <span>${formatDate(order.statusTime)}</span>
            </div>
        `;
        break;
        
    case 4: // 待付款
        metaHtml += `
            <div class="meta-group">
                <span class="meta-label">需付款:</span>
                <span class="text-danger fw-bold">¥${order.goodPrice.toFixed(2)}</span>
            </div>
            <div class="meta-group">
                <span class="meta-label">付款截止:</span>
                <span>${formatDate(order.payDeadline)}</span>
            </div>
        `;
        break;
}
    
    return metaHtml;
}

//添加修改商品事件处理
$(document).on('click', '.btn-edit-product', function() {
    const goodsId = $(this).data('goods-id');
    window.location.href = 'editProduct.jsp?goodsId=' + goodsId;
});

// 获取取消原因
function getCancelReason(order) {
    const statusId = order.statusId;
    
    if (statusId === 0) {
        return '官方封禁';
    } else if (statusId === order.buyerId) {
        return '买家取消';
    } else if (statusId === order.sellerId) {
        return '卖家取消';
    } else {
        return '未知原因';
    }
}

// 格式化日期
function formatDate(timestamp) {
    if (!timestamp) return '未知时间';
    const date = new Date(timestamp);
    return date.toLocaleString();
}